namespace iReaper
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.IO;
    using System.Web;

    public class LogManager
    {
        private static Queue<LogRequest> logQueue = new Queue<LogRequest>();
        private static ManualResetEvent wakeUp = new ManualResetEvent(false);
        public static Thread Thread = null;
        public static StringWriter sw = new StringWriter();
        public static void Init()
        {
            if (Thread == null || !Thread.IsAlive)
            {
                Thread = new Thread(new ThreadStart(LogManager.EngineEntry));
                Thread.Start();
            }
        }

        public static void AddRequest(LogRequest request)
        {
            lock (logQueue)
            {
                logQueue.Enqueue(request);
            }
            wakeUp.Set();
        }

        public static void EngineEntry()
        {
            Queue<LogRequest> queue;
            while (true)
            {
                Monitor.Enter(queue = logQueue);
                try
                {
                    if (logQueue.Count == 0)
                    {
                        wakeUp.Reset();
                    }
                }
                finally
                {
                    Monitor.Exit(queue);
                }
                wakeUp.WaitOne();
                LogRequest request = null;
                lock (logQueue)
                {
                    request = logQueue.Dequeue();
                }
                try
                {
                    DataManager.Log(request);
                }
                catch (Exception ex)
                {
                    sw.WriteLine("<p>");
                    sw.Write(ex.Message + ex.StackTrace);
                    sw.WriteLine("</p>");
                }
            }
        }
    }
}
